package com.yuanlai.quartz.utils;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.DateBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.DateBuilder.IntervalUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yuanlai.quartz.model.vo.TaskVo;



@Component
public class QuartzUtil {
	public final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private Scheduler scheduler;	
	/**
	 * 根据Job的全路径类名，生成Trigger名
	 * @param fullJokClassName
	 * @return
	 */
	public String generateDefaultTriggerName(String fullJokClassName) {
		return fullJokClassName+"Trigger";
	}
	
	/**
	 * 把任务添加到调度器
	 * @param task
	 */
	@SuppressWarnings("unchecked")
	public void addJobToStartSchedule(TaskVo task)  {
		Class<? extends Job> jobClass;
		
		try {
			jobClass = (Class<? extends Job>) Class.forName(task.getBeanClass());
	        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(task.getJobName(), task.getJobGroup())// 任务名称和组构成任务key
	                .build();
	        // 定义调度触发规则
	        // 统一使用cronTrigger
	        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(task.getJobName()+"-"+task.getId(), task.getJobGroup())//触发器key
	                .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))
	                .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression())).startNow().build();
	        // 把job和trigger注册到任务调度中
	        scheduler.scheduleJob(jobDetail, trigger);
	        // 启动
	        if (!scheduler.isShutdown()) {
	            scheduler.start();
	          }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.error(e);
		}
	}
	
	/**
	 * 立即执行一次
	 * @param task
	 * @throws SchedulerException
	 * @throws ClassNotFoundException 
	 */
	public void runJobNow(TaskVo task) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());		
		
		log.info("立即执行一次，任务名称："+task.getJobName()+"，任务组："+task.getJobGroup()+",任务类名："+task.getBeanClass());
        scheduler.triggerJob(jobKey);
		
	}
	/**
	 * 删除任务
	 * @param task
	 * @throws SchedulerException
	 */
	public void deleteJob(TaskVo task) throws SchedulerException {
		 JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
		  if (jobKey!=null) {
			  scheduler.deleteJob(jobKey);
		 }
	    

	}
	
	/**
	 * 恢复任务
	 * @param task
	 * @throws SchedulerException
	 */
	public void resumeJob(TaskVo task) throws SchedulerException {
		 JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
		 if (jobKey!=null) {
	      scheduler.resumeJob(jobKey);
		 }
	}
	/**
	 * 暂停任务
	 * @param task
	 * @throws SchedulerException
	 */
	public void pauseJob(TaskVo task) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
		if (jobKey!=null) {
			scheduler.pauseJob(jobKey);
		}
	      
	}
	
	/**
	 * 更新cron表达式
	 * @param task
	 * @throws SchedulerException 
	 */
	public void updateCronExpression(TaskVo task) throws SchedulerException {
		TriggerKey triggerKey = TriggerKey.triggerKey(task.getJobName()+"-"+task.getId());
		CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCronExpression());
		cronTrigger.getTriggerBuilder().withIdentity(triggerKey)
		                               .withSchedule(cronScheduleBuilder)
		                               .build();
		//重启触发器
		scheduler.rescheduleJob(triggerKey, cronTrigger);
		
		
	}
}
